package com.zy.listener;


import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;
import com.zy.entity.base.BaseEntity;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MybatisEntityListener implements InsertListener, UpdateListener {

    private String getCurrentUser() {
        Object username = StpUtil.getLoginId(); // 获取当前登录账号
        return username != null ? username.toString() : "system";
    }

    @Override
    public void onInsert(Object entity) {
        if (entity instanceof BaseEntity base) {
            String user = getCurrentUser();
            LocalDateTime now = LocalDateTime.now();

            base.setCreator(user);
            base.setCreateTime(now);
            base.setUpdator(user);
            base.setUpdateTime(now);
        }
    }

    @Override
    public void onUpdate(Object entity) {
        if (entity instanceof BaseEntity base) {
            base.setUpdator(getCurrentUser());
            base.setUpdateTime(LocalDateTime.now());
        }
    }
}
